// test/canvasTest/canvasTest.js
import {imgCompress} from "../../utils/img";

Page({

  /**
   * 页面的初始数据
   */
  data: {

  },

  chooseUpload(e) {
    let { field, uploadImgs, uploadFiles, dis, } = this.data,
      { type,picCount = 9,compress,watermark } = field
    if(type === 'picture') {
      let len = picCount - uploadImgs.length
      if(!len) return
      //231201 yan 控制图片选择来源方式
      let sourceType = [];
      if (field.is_take_a_photo) sourceType.push('camera')
      if (field.is_upload_picture) sourceType.push('album')
      if (!sourceType.length) sourceType.push('camera')
      // if (field.allowUpload !== undefined && !field.allowUpload) {sourceType = [ 'camera']}
      //231201 end
      wx.chooseMedia({
        count: len > 9 ? 9 : len,
        mediaType: ['image'],
        sourceType,
        // sizeType:
        success: (res) => {
          let files = res.tempFiles,
            proArr = [];


          // 230914 yan 测试用：临时地址显示图片
          /* files.forEach(item => {
             uploadImgs.push(item.tempFilePath, )
           })
           this.setData({
             uploadImgs,
           })
           this.triggerChange(uploadImgs.join(','))
           */

          //231018 yan 增加水印功能
          new Promise(resolve => {
            //231215 yan 为兼容未登录时上传功能，增加字段参数传入时传入上传文件接口方法
            let uploadFn = field.uploadMethod || wx.$uploadReq
            files.forEach(async (item,i )=> {
              //240309 yan 注释 取消判断compress
              // if (compress){
              // let opts = watermark ? watermark() : '';
              // console.log(opts);
              let fn = () => this.getWatermarkData(watermark)
              if (typeof watermark === 'function'){
                fn = watermark
              }
              fn().then(async opts => {
                await imgCompress(item,opts,this).then(res => {
                  proArr.push(uploadFn(res.tempFilePath, ))
                  if (i === files.length-1){
                    resolve();
                  }
                });
              }).catch(() => {})

              //   return
              // }
              //231018 end

              /*proArr.push(uploadFn(item.tempFilePath, ));
            //231215 end
              if (i === files.length-1){
                resolve();
              }*/
            })
          }).then(() => {
            //231215 yan 修改，上传图片只提交文件名称
            wx.showLoading({mask: true})
            Promise.all(proArr).then(res => {
              wx.hideLoading()
              let {field_long} = field
              res.forEach(item => {
                let { data, response, } = item,
                  { errcode, } = response,
                  { row, } = data
                // if(errcode === 0 && row[0] && row[0].data) uploadImgs.push(row[0].data)

                if(errcode === 0 && row[0] && row[0].data) {
                  let name = row[0].filename
                  //240313 yan 增加判断字段长度
                  if (field_long && (uploadImgs.join(',').length + name.length+1) > field_long) {
                    wx.$toast('上传图片超出长度')
                    return;
                  }
                  //240313 end
                  uploadImgs.push(name)
                }
              })
              //231215 end
              this.setData({
                uploadImgs,
              })
              this.triggerChange(uploadImgs.join(','))
            })
          })

        },
      })
    } else {
      let len = 9 - uploadFiles.length
      if(!len) return
      wx.chooseMessageFile({
        count: len,
        type: 'all',
        success: (res) => {
          // tempFilePath可以作为 img 标签的 src 属性显示图片
          let files = res.tempFiles,
            proArr = []
          //231215 yan 为兼容未登录时上传功能，增加字段参数传入时传入上传文件接口方法
          let uploadFn = field.uploadMethod || wx.$uploadReq
          files.forEach(item => {
            proArr.push(uploadFn(item.path, item.name))
          })
          //231215 end
          Promise.all(proArr).then(res => {
            res.forEach(item => {
              let { data, response, } = item,
                { errcode, } = response,
                { row, } = data
              if(errcode === 0 && row[0] && row[0].data) uploadFiles.push(row[0].data)
            })
            this.setData({
              uploadFiles,
            })
            this.triggerChange(uploadFiles.join(','))
          })

        }
      })
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})
